<template>
    <div class="app-container" v-loading="loading" element-loading-text="上传中">
        <div style="display: flex;flex-direction: column;align-items: center;">
            <el-form ref="form" :model="upload" :rules="rules" label-width="80px">
                <el-form-item label="上传文件" prop="fileName">
                    <el-upload ref="upload" :limit="1" :accept="upload.accepts" :headers="upload.headers"
                        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false"
                        :on-change="handleFileChange" :on-error="handleFileError" :show-file-list="false">
                        <div style="display: flex;flex-direction: row;align-items: center;">
                            <el-input v-model="upload.fileName" placeholder="请选择文件" :readonly="true"
                                style="width: 220px;" slot="trigger"></el-input>
                            <div style="width: 10px;"></div>
                            <!--  <el-button size="small" type="primary">点击上传</el-button> -->
                            <div slot="tip" class="el-upload__tip" style="line-height: unset;">只能上传xls文件</div>
                        </div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="数据类型" prop="selectType">
                    <el-select v-model="upload.selectType" placeholder="请选择" size="small" style="width: 220px;">
                        <el-option v-for="item in dict.type.admission_type" :key="item.value" :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">导 入</el-button>
            </div>
        </div>
    </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { imp } from "@/api/system/admission";
export default {
    name: "admitDr",
    dicts: ['admission_type'],
    data() {
        return {
            loading:false,
            form: {},
            rules: {
                fileName: [{ required: true, type: 'string', message: "文件不能为空", trigger: "blur || change" }],
                selectType: [
                    { required: true, message: "数据类型不能为空", trigger: "change" },
                ],
            },
            upload: {
                // 是否显示弹出层（用户导入）
                open: false,
                // 弹出层标题（用户导入）
                title: "",
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的用户数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: { Authorization: "Bearer " + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + "/common/upload",
                fileName: "",
                accepts: '.xls', //修改注意下面拦截
                selectType: "",
                tempFileList: [] //缓存文件列表
            }
        }
    },
    methods: {
        handleFileUploadProgress(res, fileList) { },
        handleFileChange(res, fileList) {
            console.log("更新", res.name)
            this.upload.tempFileList = fileList
            let resName = res.name
            let splitResName = resName.split(".")
            splitResName = splitResName[splitResName.length - 1]
            if (splitResName != 'xls') {
                this.$message.error("请选择规定类型的文件");
                return
            } else {
                this.$set(this.upload, 'fileName', res.name)
            }
        },
        //上传失败回调
        handleFileError(err, file, fileList) {
            this.loading = false
            this.$message({
                message: err,
                type: 'error',
                duration: 9000
            });
            this.$refs.upload.clearFiles();
        },
        // 上传成功回调
        async handleFileSuccess(res, file) {
            this.loading = false
            if (res.code == 200) {
                let parmas = {
                    filePath: res.fileName,
                    dataType: this.upload.selectType
                }
                await imp(parmas).then((response) => {
                    console.log(response)
                    if (response.msg == "成功") {
                        this.$modal.msgSuccess("导入成功");
                        this.upload.fileName = ""
                        this.upload.tempFileList = []
                    } else {
                        this.$message({
                            message: response.msg,
                            type: 'error',
                            duration: 9000,
                            dangerouslyUseHTMLString:true
                        });
                    }
                }).catch((e) => {
                    console.log(e)
                });
            } else {
                this.$message({
                    message: res.msg,
                    type: 'error',
                    duration: 9000
                });
            }
            this.$refs.upload.clearFiles();
            // this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
        },

        submitForm() {
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    this.loading = true
                    if (this.upload.tempFileList.length > 0) {
                        this.$refs.upload.clearFiles()
                        this.$nextTick(() => {
                            this.$refs.upload.handleStart(this.upload.tempFileList[0].raw)
                            this.$refs.upload.submit();
                        })
                    } else {
                        this.$refs.upload.submit();
                    }
                    console.log("提交", this.upload)
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped></style>